package com.shanjupay.merchant.service;

import com.alibaba.nacos.client.utils.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shanjupay.common.domain.BusinessException;
import com.shanjupay.common.domain.CommonErrorCode;
import com.shanjupay.merchant.api.AppService;
import com.shanjupay.merchant.api.dto.AppDTO;
import com.shanjupay.merchant.convert.AppConvert;
import com.shanjupay.merchant.entity.App;
import com.shanjupay.merchant.entity.Merchant;
import com.shanjupay.merchant.mapper.AppMapper;
import com.shanjupay.merchant.mapper.MerchantMapper;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

//dubbo的Service接口
@Service
public class AppServiceImpl implements AppService {

    @Autowired
    private AppMapper appMapper;
    @Autowired
    private MerchantMapper merchantMapper;

    @Transactional
    @Override
    public AppDTO createApp(AppDTO dto) {
        //参数校验
        if (dto==null || dto.getMerchantId()==null|| StringUtils.isBlank(dto.getAppName())){
            throw new BusinessException(CommonErrorCode.E_110006);
        }
        //检查商户是否通过资质审核
        //由产品经理告知 创建应用时候 校验商户是否通过资质审核
        Merchant merchant = merchantMapper.selectById(dto.getMerchantId());
        if (merchant==null){
            throw new BusinessException(CommonErrorCode.E_200202);
        }
        String auditStatus = merchant.getAuditStatus();
        if(!"2".equals(auditStatus)){
            throw new BusinessException(CommonErrorCode.E_200003);
        }

        Integer count = appMapper.selectCount(Wrappers.<App>lambdaQuery().eq(App::getAppName, dto.getAppName()));
        if (count>0){
            throw new BusinessException(CommonErrorCode.E_200004);
        }

        //对象转换
        App app = AppConvert.INSTANCE.dto2Entity(dto);
        //补全Entity数据 app_id 使用UUID生成
        String app_id= UUID.randomUUID().toString();
        app.setAppId(app_id);

        //插入数据到数据库
        appMapper.insert(app);
        //补全dto数据 app_id 使用UUID生成
        dto.setAppId(app_id);
        return dto;
    }


}
